package jp.gr.java_conf.homeems.gw.internal.measurementdatamanager;

import java.util.Dictionary;
import java.util.Hashtable;

import jp.gr.java_conf.homeems.gw.common.exception.GwException;
import jp.gr.java_conf.homeems.gw.measurementdatamanager.MeasurementDataManagerService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

public class MeasurementDataManagerActivator implements BundleActivator {

	private static BundleContext context;
	private ServiceRegistration<MeasurementDataManagerService> measurementDataManagerServiceRegistration;

	static BundleContext getContext() {
		return context;
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext bundleContext) throws Exception {
		MeasurementDataManagerActivator.context = bundleContext;
		
		registerService(bundleContext);
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext bundleContext) throws Exception {
		MeasurementDataManagerActivator.context = null;
		
		unregisterService();
	}
	
	private void registerService(BundleContext context) throws GwException
	{
		MeasurementDataManagerServiceImpl measurementDataManagerServiceImpl = new MeasurementDataManagerServiceImpl();
		
		Dictionary<String, String> measurementDataManagerServiceProperties = new Hashtable<String, String>();
		measurementDataManagerServiceProperties.put("service.pid", MeasurementDataManagerService.class.getName());
		
		this.measurementDataManagerServiceRegistration = context.registerService(MeasurementDataManagerService.class
																					, measurementDataManagerServiceImpl
																					, measurementDataManagerServiceProperties);
		
		if (this.measurementDataManagerServiceRegistration == null) 
		{
			throw new GwException("EMDMxxx", "xxx");
		}
	}
	
	private void unregisterService()
	{
		if (this.measurementDataManagerServiceRegistration != null)
		{
			this.measurementDataManagerServiceRegistration.unregister();
			this.measurementDataManagerServiceRegistration = null;
		}
	}
}
